/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.sharedbills.client.form;

import java.util.Date;

import org.jb.sharedbills.client.gin.EventId;
import org.jb.sharedbills.client.stores.MessageStore;
import org.jb.sharedbills.shared.dto.Message;
import org.jb.sharedbills.shared.svc.MessageServiceAsync;

import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ToolButton;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class MessagePanel extends ContentPanel {

	private String eventId;
	private MessageServiceAsync messageService;
	private MessageStore messageStore;

	@Inject
	public MessagePanel( @EventId String eventId, 
						 MessageServiceAsync messageService,
						 final MessageStore store) {
		
		this.eventId = eventId;
		this.messageService = messageService;
		this.messageStore = store;
		
		setHeaderVisible(true);
		setHeading("Messages");
		setFrame(true);
		setHeight(70);
		setLayout( new FitLayout() );

		ListView<BeanModel> listView = new ListView<BeanModel>() {

			DateTimeFormat dateFormat = DateTimeFormat.getFormat("HH:mm dd/MM/yy");
			
			@Override
			protected BeanModel prepareData(BeanModel model) {
				Message msg = model.getBean();
				Date date = msg.getDate();
				if (date != null) {
					model.set("datestr", dateFormat.format(date) );
				}
				return super.prepareData(model);
			}
			
		};
		listView.setTemplate(getTemplate());
		listView.setItemSelector("div.message-item");  
		listView.setStore(store);
		listView.setLoadingText("Chargement...");
		listView.setSelectStyle("");
		listView.setOverStyle("");
		
		setScrollMode(Scroll.AUTOY);
		
		add( listView );

		ToolButton addBtn = new ToolButton("x-tool-plus");
		addBtn.addListener(Events.Select, new Listener<ComponentEvent>() {
	    	public void handleEvent(ComponentEvent ce) {
	    		ce.stopEvent();
	    		GWT.runAsync( new ModalRunAsync() {
					@Override
					void execute() {
						MessageWriteDialog dlg = new MessageWriteDialog();
			    		dlg.show();
					}
				});
	    	}
	    });
		
		getHeader().addTool( addBtn );
		ToolButton loadBtn = new ToolButton("x-tool-refresh");
		loadBtn.addListener(Events.Select, new Listener<ComponentEvent>() {
	    	public void handleEvent(ComponentEvent ce) {
	    		ce.stopEvent();
	    		
	    		store.getLoader().load();
	    	}
	    });
		getHeader().addTool( loadBtn );
	}
	
	/**
	 * 
	 * @return
	 */
	private native String getTemplate() /*-{ 
    return ['<tpl for=".">', 
    '<div class="message-item">',
    '<b>{from}</b>, <i>{datestr}</i>',
    '<div style="border-left: 1px solid; margin-left: 5px; padding-left: 5px">{message}</div>',
    '</div>', 
    '</tpl>', 
    '<div class="x-clear"></div>'].join(""); 
     
    }-*/;
	
	public class MessageWriteDialog extends Window {
		
		public MessageWriteDialog() {
			setPlain(true);  
			setSize(550, 400);  
			setHeading("Nouveau message");  
			setLayout(new FitLayout());  
			setModal(true);
	  
			FormPanel panel = new FormPanel();  
			panel.setBorders(false);  
			panel.setBodyBorder(false);  
			panel.setLabelWidth(55);  
			panel.setPadding(5);  
			panel.setHeaderVisible(false);  
	  
			final TextField<String> field = new TextField<String>();  
			field.setFieldLabel("Pseudo");  
			field.setAllowBlank(false);
			panel.add(field, new FormData("96%"));   
	  
			final HtmlEditor html = new HtmlEditor();  
			html.setHideLabel(true);  
			panel.add(html, new FormData("100% -25"));  
	  
			Button btnSend = new Button("Envoyer");
			btnSend.addSelectionListener( new SelectionListener<ButtonEvent>() {
				
				@Override
				public void componentSelected(ButtonEvent ce) {
					String pseudo = field.getValue();
					if (pseudo == null || pseudo.isEmpty())
						return;
					
					String msg = html.getValue();
					if (msg == null || msg.isEmpty() || msg.contains("<script"))
						return;
					
					final Message message = new Message();
					message.setFrom( pseudo );
					message.setMessage( msg );
					message.setDate( new Date() );
					
					final MessageBox wait = MessageBox.wait("Message", "Emission du message...", "");
					wait.show();
					messageService.postMessage( eventId, message, new AsyncCallback<Void>() {
						
						@Override
						public void onSuccess(Void result) {
							wait.close();
							messageStore.addNewMessage(message);
							hide();
						}
						
						@Override
						public void onFailure(Throwable caught) {
							wait.close();
							Info.display("Message", "Impossible de poster le message");
						}
					});
					
				}
			});
			addButton(btnSend);  
			addButton(new Button("Annuler"));  
			add(panel);  
			
			setFocusWidget(field);
		}
	  

	}
}
